package com.joeyzh.iframe.db;

import android.database.Cursor;

import org.greenrobot.greendao.AbstractDao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * Created by Joey on 2018/5/25.
 * 数据库处理的工具类
 * @author Joey
 */

public abstract class BaseDbEntityDaoUtil<Entity extends BaseDbEntity, EntityDao extends AbstractDao<Entity, ?>> {

    DBManagerUtil mManager = DBManagerUtil.getInstance();

    /**
     * 插入
     *
     * @param entity
     */
    public boolean insert(Entity entity) {
        long i = mManager.getDaoSession().insertOrReplace(entity);
        if (i > 0) {
            return true;
        }
        return false;
    }

    /**
     * 删除
     *
     * @param entity
     */
    public void delete(Entity entity) {
        mManager.getDaoSession().delete(entity);
    }

    /**
     * 更新
     *
     * @param entity
     */
    public void update(Entity entity) {
        mManager.getDaoSession().update(entity);
    }

    /**
     * 根据某个类型的
     *
     * @param
     */
    public void deleteAll() {
        Class<EntityDao> daoClass = (Class<EntityDao>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        mManager.getDaoSession().deleteAll(daoClass);
    }

    /**
     * 查询某条数据
     *
     * @param id
     * @return
     */
    public Entity queryById(String id) {
        Class<Entity> cls = (Class<Entity>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return mManager.getDaoSession().load(cls, id);
    }

    /**
     * 获取某个列表
     *
     * @param
     * @return
     */
    public List<Entity> getAll() {
        Class<Entity> cls = (Class<Entity>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return mManager.getDaoSession().loadAll(cls);
    }

    /**
     * 批量插入多条数据，在子线程操作
     *
     * @param list
     * @return
     */
    public boolean insertLots(final List<Entity> list) {
        boolean flag = false;
        try {
            mManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (Entity entity : list) {
                        insert(entity);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public int queryCount(String sql, String[] args) {
        Cursor cursor = null;
        try {
            cursor = mManager.getDaoMaster().getDatabase().rawQuery(sql, args);
            if (cursor.moveToNext()) {
                return cursor.getInt(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return 0;
    }
}
